package net.wanho.shiro.filter;

import net.wanho.shiro.token.JwtToken;
import net.wanho.util.ServletUtil;
import net.wanho.vo.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * JWT过滤器
 */
public class JwtFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest request = WebUtils.toHttp(servletRequest);

        /**
         * 如果前端发送跨域请求，且自定义了请求头，那么每次请求前会自动发起一个options预检请求，来获取一些服务器信息。
         * 这是浏览器自身的机制，该请求中并不含有token信息，所以对于options请求，直接放行
         */
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }

        // 判断请求头中是否有token，如果没有，则直接拒绝访问；如果有，则进行身份认证
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isEmpty(authorization)){
            ServletUtil.writeJson(AjaxResult.error(HttpStatus.UNAUTHORIZED.value(), "请先登录再操作！"));
            return false;
        }
        String token = authorization.replace("Bearer ", "");

        // 调用shiro认证
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new JwtToken(token));
        } catch (AuthenticationException e) {
            ServletUtil.writeJson(AjaxResult.error("token无效，身份认证失败！"));
            return false;
        }

        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return false;
    }
}